import { render, h } from 'vue';
import ModalCmponent from '@/components/modal.vue';

class ModalIns {
    private static ins: ModalIns = new ModalIns();

    private container: HTMLElement;

    private constructor() {
        this.container = document.createElement('div');
        this.container.style.position = 'fixed';
        this.container.style.zIndex = '99999';
        this.container.style.top = '0';
        this.container.style.right = '0';
        this.container.style.left = '0';
        this.container.style.bottom = '0';
        this.container.style.background = 'rgba(0,0,0,.2)';
    }

    public static getIns() {
        if (!this.ins) {
            this.ins = new ModalIns();
        }
        return this.ins;
    }

    show(config?: { title: string; msg: string }) {
        render(
            h(ModalCmponent, {
                ...config,
                onClose: () => {
                    this.hide();
                }
            }),
            this.container
        );
        document.body.insertBefore(this.container, document.body.firstChild);
    }

    hide() {
        document.body.removeChild(this.container);
    }
}

export const useModal = () => {
    const modal = ModalIns.getIns();

    const show = (conifg: any) => modal.show(conifg);

    const cancel = () => modal.hide();

    return { show, cancel };
};
